package com.bejoy.coolatin.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import com.bejoy.coolatin.R;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import cn.jpush.android.api.BasicPushNotificationBuilder;
import cn.jpush.android.api.JPushInterface;

public class ContextUtil {
	private Context context;
	private Dialog mDialog = null;
	SharedPreferences share = null;

	public ContextUtil(Context context) {
		this.context = context;
	}

	// // 检测网络连接
	// public boolean isConn() {
	// boolean bisConnFlag = false;
	// ConnectivityManager conManager = (ConnectivityManager) context
	// .getSystemService(Context.CONNECTIVITY_SERVICE);
	// NetworkInfo network = conManager.getActiveNetworkInfo();
	// if (network != null) {
	// bisConnFlag = conManager.getActiveNetworkInfo().isAvailable();
	// }
	// return bisConnFlag;
	// }

	// 分享微信(分享网页)
	public void shareWeiXin(Context context, IWXAPI wxApi, int number) {
		WXWebpageObject webpage = new WXWebpageObject();
		webpage.webpageUrl = "这里填写链接url";
		WXMediaMessage msg = new WXMediaMessage(webpage);
		msg.title = "这里填写标题";
		msg.description = "这里填写内容";
		// 这里替换一张自己工程里的图片资源
		Bitmap thumb = BitmapFactory.decodeResource(context.getResources(),
				R.drawable.ic_launcher);
		msg.setThumbImage(thumb);

		SendMessageToWX.Req req = new SendMessageToWX.Req();
		req.transaction = String.valueOf(System.currentTimeMillis());
		req.message = msg;
		req.scene = number == 0 ? SendMessageToWX.Req.WXSceneSession
				: SendMessageToWX.Req.WXSceneTimeline;
		wxApi.sendReq(req);
	}

	/**
	 * 获取当前应用程序的版本号。
	 */
	public int getAppVersion() {
		try {
			PackageInfo info = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0);
			return info.versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return 1;
	}

	/**
	 * 根据传入的uniqueName获取硬盘缓存的路径地址。
	 */
	public File getDiskCacheDir(String uniqueName) {
		String cachePath;
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())
				|| !Environment.isExternalStorageRemovable()) {
			cachePath = context.getExternalCacheDir().getPath();
		} else {
			cachePath = context.getCacheDir().getPath();
		}
		return new File(cachePath + File.separator + uniqueName);
	}

	/**
	 * 显示帧动画方式的等待框
	 * 
	 * @param flag
	 *            是否可以取消
	 */
	public void showProcessDialog(boolean flag) {
		OnKeyListener keyListener = new OnKeyListener() {
			@Override
			public boolean onKey(DialogInterface dialog, int keyCode,
					KeyEvent event) {
				// if (keyCode == KeyEvent.KEYCODE_HOME || keyCode ==
				// KeyEvent.KEYCODE_SEARCH)
				// {
				// return true;
				// }
				return false;
			}
		};

		mDialog = new AlertDialog.Builder(context).create();
		// mDialog.setOnKeyListener(keyListener);//加载键盘事件
		mDialog.show();
		mDialog.setCancelable(flag);
		mDialog.setContentView(R.layout.progressbar_loading_anim);// 加载滚动效果的布局文件
	}

	// 隐藏等待框
	public void dismissProcessDialog() {
//		Log.e("savvy", "关闭等待框0");
		if (mDialog != null&&mDialog.isShowing()) {
//			Log.e("savvy", "关闭等待框1111");
			mDialog.dismiss();
		}
	}

	/**
	 * @author 获取当前的网络状态 -1：没有网络 1：WIFI网络2：wap网络3：net网络
	 * @param context
	 * @return
	 */
	public int getAPNType() {
		int netType = -1;
		ConnectivityManager connMgr = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
		if (networkInfo == null) {
			return netType;
		}
		int nType = networkInfo.getType();
		if (nType == ConnectivityManager.TYPE_MOBILE) {
			Log.e("networkInfo.getExtraInfo()",
					"networkInfo.getExtraInfo() is "
							+ networkInfo.getExtraInfo());
			if (networkInfo.getExtraInfo().toLowerCase().equals("cmnet")) {
				netType = 3;
			} else {
				netType = 2;
			}
		} else if (nType == ConnectivityManager.TYPE_WIFI) {
			netType = 1;
		}
		return netType;
	}

	/**
	 * 判断WiFi网络是否可用
	 * 
	 * @param context
	 * @return
	 */
	public boolean isWifiConnected() {
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mWiFiNetworkInfo = mConnectivityManager
					.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
			if (mWiFiNetworkInfo != null) {
				return mWiFiNetworkInfo.isAvailable();
			}
		}
		return false;
	}

	/**
	 * 判断数据流量是否可用
	 * 
	 * @param context
	 * @return
	 */
	public boolean isMobileConnected() {
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mMobileNetworkInfo = mConnectivityManager
					.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
			if (mMobileNetworkInfo != null) {
				return mMobileNetworkInfo.isAvailable();
			}
		}
		return false;
	}

	/**
	 * 判断是否有网络
	 * 
	 * @param context
	 * @return
	 */
	public boolean isNetworkConnected() {
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mNetworkInfo = mConnectivityManager
					.getActiveNetworkInfo();
			if (mNetworkInfo != null) {
				return mNetworkInfo.isAvailable();
			}
		}
		return false;
	}


	// 取得设备,GSM手机的 IMEI 和 CDMA手机的 MEID.
	public String getDeviceId() {
		String deviceId = null;
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(context.TELEPHONY_SERVICE);
		deviceId = tm.getDeviceId();
		// Log.e("savvy", "deviceId:"+deviceId);
		return deviceId;
	}

	// 定义JPush样式
	public void setJPushStyle() {
		share = context.getSharedPreferences(StaticProperty.SAVEINFO,
				Activity.MODE_PRIVATE);
		BasicPushNotificationBuilder myBuilder = new BasicPushNotificationBuilder(
				context.getApplicationContext());
		myBuilder.statusBarDrawable = R.drawable.ic_launcher;
		myBuilder.notificationFlags = Notification.FLAG_AUTO_CANCEL;
		// 设置为铃声与震动都要
		if (share.getBoolean(StaticProperty.VOICEFLAG, false)
				&& share.getBoolean(StaticProperty.SHAKEFLAG, false)) {
			myBuilder.notificationDefaults = Notification.DEFAULT_SOUND
					| Notification.DEFAULT_VIBRATE
					| Notification.DEFAULT_LIGHTS;
			// 有声音，无振动
		} else if (share.getBoolean(StaticProperty.VOICEFLAG, false)) {
			myBuilder.notificationDefaults = Notification.DEFAULT_SOUND
					| Notification.DEFAULT_LIGHTS;
			// 有震动，无声音
		} else if (share.getBoolean(StaticProperty.SHAKEFLAG, false)) {
			myBuilder.notificationDefaults = Notification.DEFAULT_VIBRATE
					| Notification.DEFAULT_LIGHTS;
		} else {// 无声音，无振动
			myBuilder.notificationDefaults = Notification.DEFAULT_LIGHTS;
		}
		JPushInterface.setPushNotificationBuilder(1, myBuilder);
	}

	/**
	 * 返回系统资源图片
	 * 
	 * @param uri
	 *            系统地址
	 * @param size
	 *            指定大小
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public Bitmap getThumbnail(Uri uri, int size) throws FileNotFoundException,
			IOException {
		InputStream input = this.context.getContentResolver().openInputStream(
				uri);
		BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
		onlyBoundsOptions.inJustDecodeBounds = true;
		onlyBoundsOptions.inDither = true;// optional
		onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// optional
		BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
		input.close();
		if ((onlyBoundsOptions.outWidth == -1)
				|| (onlyBoundsOptions.outHeight == -1))
			return null;
		int originalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth) ? onlyBoundsOptions.outHeight
				: onlyBoundsOptions.outWidth;
		double ratio = (originalSize > size) ? (originalSize / size) : 1.0;
		BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
		bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio);
		bitmapOptions.inDither = true;// optional
		bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// optional
		input = this.context.getContentResolver().openInputStream(uri);
		Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
//		bitmap.compress(Bitmap.CompressFormat.JPEG, 30, bitmapOptions); 
		input.close();
		return bitmap;
	}

	private static int getPowerOfTwoForSampleRatio(double ratio) {
		int k = Integer.highestOneBit((int) Math.floor(ratio));
		if (k == 0)
			return 1;
		else
			return k;
	}
	
	// 将字符串转换成Bitmap类型
	public Bitmap stringtoBitmap(String string) {
		Bitmap bitmap = null;
		try {
			byte[] bitmapArray;
			bitmapArray = Base64.decode(string, Base64.DEFAULT);
			try {
				bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0,
						bitmapArray.length);
			} catch (OutOfMemoryError error) {
				if (bitmap != null && !bitmap.isRecycled()) {
					bitmap.recycle();
					bitmap = null;
				}
				System.gc();
				System.runFinalization();
				bitmap=BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bitmap;
	}
}
